<?php

class CategoriesController extends Zend_Controller_Action {
	public function preDispatch() { 
		$auth = Zend_Auth::getInstance(); 
		if (!$auth->hasIdentity()) { 
			$this->_redirect('login'); 
		}
		else {
			if(!NerdPass_Acl::isAllowed($auth->getIdentity(), 'passwords')) {
				$this->_forward('denied', 'error');
			}
			
		}
	}

	public function addAction() {
		if (isset($_POST['newcat'])) {
			// Validate fields
			if (Zend_Validate::is($_POST['newcat'], 'Alnum', array(true))) {
				NerdPass_Data::addCategory($_POST['newcat']);
				$this->view->messages = array("Category added successfully!");
			}
			else {
				$this->view->messages = array("Category can only contain numbers and letters.");
			}
			$messagesNamespace = new Zend_Session_Namespace('Messages');
			$messagesNamespace->messages = $this->view->messages;
		}
		
		$this->view->categories = NerdPass_Data::getCategories();
		$this->view->passwords = NerdPass_Data::getPasswords();
		
		// Get uid
		$request = $this->getRequest();
		$uid = $request->getParam('uid');
		$this->view->uid = $uid;
		
		if (!isset($_SERVER['HTTP_REFERER'])) {
			$refurl = '/';
		}
		else {
			$refurl = $_SERVER['HTTP_REFERER'];
		}
		//$this->view->returnUrl = $refurl;
		$this->_redirect($refurl);
	}
	
	public function deleteAction() {
		// Get uid
		$request = $this->getRequest();
		$uid = $request->getParam('uid');
		
		NerdPass_Data::deleteCategory($uid);
		
		if (!isset($_SERVER['HTTP_REFERER'])) {
			$refurl = '/';
		}
		else {
			$refurl = $_SERVER['HTTP_REFERER'];
		}
		$this->_redirect($refurl);
	}
}